/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.organization;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.service.system.ManagementAccountService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.entity.MerchantGroup;
import com.qinyeit.serviceapp.service.organization.MerchantGroupService;

import org.apache.commons.codec.language.bm.Lang;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * ClassName: MerchantGroupsController <br/>
 * Function: merchantGroup [连锁店] <br/>
 * date: 2018-11-20 11:05:18 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/organization/merchantGroups")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_merchantGroup:read",name ="连锁店",deleteAble = false)
public class MerchantGroupsController extends BaseManagementController{

	@Autowired
	private MerchantGroupService merchantGroupService;
	@Autowired
	private ManagementAccountService managementAccountService;
    //TODO include的字段,支持jsonPath
	private final String [] keys = {"id","companyName","linker","phone","telephone","address"};

    @RequiresPermissions("management_merchantGroup:show")
    @PermissionInfo(code = "management_merchantGroup:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        Page<MerchantGroup> merchantGroupPage = merchantGroupService.findAll(searchable);
        return ok("查询成功", JSONUtils.include(merchantGroupPage, keys));
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("merchantGroup",JSONUtils.include(new MerchantGroup(), keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_merchantGroup:create")
    @PermissionInfo(code = "management_merchantGroup:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid MerchantGroup merchantGroup, BindingResult bindingResult){
//        if(merchantGroupService.exists(buildExists(null, "no", merchantGroup.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        merchantGroupService.save(merchantGroup);
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute MerchantGroup merchantGroup){
        return ok("查询成功", JSONUtils.include(merchantGroup, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute MerchantGroup merchantGroup){
        QyMap map=QyMap.NEW();
        map.setv("merchantGroup",JSONUtils.include(merchantGroup, keys));
        initFormDate(map);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_merchantGroup:update")
    @PermissionInfo(code = "management_merchantGroup:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid MerchantGroup merchantGroup,BindingResult bindingResult){
//        if(merchantGroupService.exists(buildExists(null, "no", merchantGroup.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        merchantGroupService.update(merchantGroup);
        return ok("更新成功", null);
    }


    /**
     * 连锁商户组注册
     * @param json
     * @return
     */
    @RequestMapping(value = "/registerMerchantGroups",method = RequestMethod.POST)
    public Object registerMerchantGroups(@RequestBody JSONObject json){
        MerchantGroup merchantGroup = merchantGroupService.registerMerchantGroups(json);
        log.info("注册岑巩 :  ");
        return ok("注册成功");
    }

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @RequestMapping(value = "/sendCode", method = RequestMethod.GET)
    public Object sendCode(String phone) {
        merchantGroupService.sendCode(phone);
        return ok("发送成功");
    }

    /**
     * 验证信息
     * @param json
     * @return
     */
    @RequestMapping(value = "/verify", method = RequestMethod.POST)
    public Object verify(@RequestBody JSONObject json) {
        merchantGroupService.verify(json);
        return ok("验证成功");
    }

    @RequiresPermissions("management_merchantGroup:destory")
    @PermissionInfo(code = "management_merchantGroup:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        merchantGroupService.logicDelete(id);
        return ok("删除成功", null);
    }


    /**
     * 修改密码
     * @param oldpass 原密码
     * @param newpass 新密码
     * @param confirmpass 确认密码
     * @return
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    @RequiresPermissions("management_merchantGroup:changePassword")
    public Object changePassword(String oldpass,String newpass,String confirmpass) {
//        merchantAccountService.changePassword(oldpass,newpass,confirmpass);
        managementAccountService.updateAccountPassword(oldpass,newpass,confirmpass, CurrentAccountUtils.getAuthenticatedAccountID());
        return ok("修改密码成功");
    }


    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            MerchantGroup merchantGroup = merchantGroupService.findById(Long.valueOf(id));
            model.addAttribute(merchantGroup);
        }
    }





    /**
     * 初始化打印配置
     * @return
     */
    @RequestMapping(value = "/initPrint", method = RequestMethod.GET)
    public Object initPrint(Long merchantGroupId) {
        boolean boo = merchantGroupService.orderPrintSetFormat(merchantGroupId);
        return ok("操作成功",boo);
    }



    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //TODO 这里加入表单中需要的初始化数据
        //qyMap.setv("","").setv("","").setv("","")
    }

}